package command;

import model.impl.TicketImpl;
import DTO.ScheduleDTO;
import DTO.TicketDTO;

import com.gmail.at.vssabinin.train_transport_system_part1.Protocol;
import com.gmail.at.vssabinin.train_transport_system_part1.ReceivedData;

/**
 * Class represents command interface;
 * It sends a message to the client user. Message contains information
 * whether it was successful to buy desirable ticket, and if it was,
 * it sends back TicketDTO object and message OK, else message no and
 * string object, why the operation failed.
 */
public class ClientBuyTicket implements Command {

	private Protocol protocol = new Protocol();
	
	@Override
	public void execute(ReceivedData recived) {
		model.Ticket ticketImpl = new TicketImpl();
		Protocol.Message message = this.protocol.decodeMessage(recived.data);
		ScheduleDTO scheduleDTO = (ScheduleDTO) message.getObject();
		TicketDTO ticket = ticketImpl.buyTicket(scheduleDTO, recived.server.authorizedUsers
				.get(recived.socket));
		if (ticket == null){
			Protocol.Message answer = this.protocol.new Message("no", "Sorry, no available " +
					"places!");
			recived.server.send(recived.socket, this.protocol.createMessage(answer));
		} else if (ticket.getTicketID() == -1){
			Protocol.Message answer = this.protocol.new Message("no", "You already have " +
					"the ticket on this train!");
			recived.server.send(recived.socket, this.protocol.createMessage(answer));
		} else if (ticket.getTicketID() == -2){
			Protocol.Message answer = this.protocol.new Message("no", "It's to late to buy " +
					"this ticket, it's less, than 10 minutes to departure!");
			recived.server.send(recived.socket, this.protocol.createMessage(answer));	
		} else {
			Protocol.Message answer = this.protocol.new Message("ok", ticket);
			recived.server.send(recived.socket, this.protocol.createMessage(answer));
		}
	}
}
